<?php

/**
 * publication actions.
 *
 * @package    Redsea20
 * @subpackage publication
 * @author     Your name here 
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class publicationActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
      
      return sfView::SUCCESS;
      
  }
public function executeLoadpublications(sfWebRequest $request) {
    /*
     * This publication module is being called from Home Screen, User PRofile screen
     * and Publication Tab (before Login).
     * 
     * So if user is not logged in then uid (userid) would be null
     */
    $this->userId = $request->getParameter('uid');
    $this->tabId = $request->getParameter('tid');

    /* At user profile screen, we need to show one tab with username only
     * $showUserTab flag is being used for that purpose.
     *
     * Ref: http://www.almacode.com:12003/issues/86
     */
    $showUserTab = $request->getParameter('showUserTab');

    // If request is coming from userProfile screen then hide tabs
    // as we don't need tabs at userProfile screen
    $showTabs = $request->getParameter('st');

    $this->showTabs = isset ($showTabs)&& $showTabs == '1';
    $this->showUserTab = isset ($showUserTab) && $showUserTab == '1';
 
    return sfView::SUCCESS;
}

   public function executeRefreshRBISResearchList(sfWebRequest $request) {
       $selectTabValue = $request->getParameter('tid');
       $researchSearchtext = $request->getParameter('rSearchtext');
       $pgNumber = $request->getParameter('pg');
       $entityId = $request->getParameter('id');

      /*
       * EntityID (i-e id url parameter) is encoded in Home/Index Line 63
       * So it must be decoded before use
       *
       * Note: Encoded with htmlspecialchars( base64_encode () )
       */
      // Fetches the publication list 
      switch ($selectTabValue) {
          case Types::$RESEARCH_TABS[Types::$RESEARCH_TABS_ALL]:
              $this->researchList = Research::getResearchListByStatus(NULL, array(Types::$RESEARCH_SCOPE[Types::$RESEARCH_SCOPE_PUBLIC]), $entityId, $pgNumber, $researchSearchtext, FALSE, FALSE);
              break;
          case Types::$RESEARCH_TABS[Types::$RESEARCH_TABS_MINE]:
              $this->researchList = Research::getResearchListByStatus(NULL, array(Types::$RESEARCH_SCOPE[Types::$RESEARCH_SCOPE_PUBLIC], Types::$RESEARCH_SCOPE[Types::$RESEARCH_SCOPE_PRIVATE]), $entityId, $pgNumber, $researchSearchtext, TRUE, FALSE);
              break;
          case Types::$RESEARCH_TABS[Types::$RESEARCH_TABS_COLLABORATION]:
              $this->researchList = Research::getResearchListByStatus(NULL, array(Types::$RESEARCH_SCOPE[Types::$RESEARCH_SCOPE_PUBLIC], Types::$RESEARCH_SCOPE[Types::$RESEARCH_SCOPE_PRIVATE]), $entityId, $pgNumber, $researchSearchtext, TRUE, TRUE);
              break;
          case Types::$RESEARCH_TABS[Types::$RESEARCH_TABS_PENDING_APPROVAL]:
              $this->researchList = ResearchTable::getInstance()->getAllApprovalRequestsByStatus(Types::$RESEARCH_APPROVAL_STATUS[Types::$APPR_AWAITING], $this->getUser()->getAttribute('currentuser')->getId(), $pgNumber, $researchSearchtext);
              //$this->researchList = Research::getResearchListByStatus(NULL, array(Types::$RESEARCH_SCOPE[Types::$RESEARCH_SCOPE_PUBLIC], Types::$RESEARCH_SCOPE[Types::$RESEARCH_SCOPE_PRIVATE]), $entityId, $pgNumber, $researchSearchtext, TRUE);
              break;
      }
      //$this->researchList = Research::getResearchListByStatus($researchStatus, ( isset ($showMine) && $showMine == '1'? $this->getUser()->getAttribute("currentuser")->getId() : (isset($entityId)? RBISUtility::decryptURLParamValue($entityId) : NULL) ), $pgNumber,$researchSearchtext);

      /*
       * Storing selected tab value as it is being referenced in template file
       * to hide the Approve/Reject links if current tab is other than Pending Request tab
       */
      $this->selectedTab = $selectTabValue;

      // Hides the "More++" link if it is last page
      $this->hasNextPage = $pgNumber < $this->researchList->getLastPage();
      
      return sfView::SUCCESS;
  }

    /*
     * Gets the list of rbis users so that current user can invite any other
     * user for collaboraton {Ref: Fahmi 04/13/2011}
     */
    public function executeCollaborationUserAutocomplete(sfWebRequest $request)
    {
      $currentUser = $this->getUser()->getAttribute("currentuser");

      $connInfo = '';
      $rbisUserList = $currentUser->getRBISUserList();
      foreach($rbisUserList as $rbisUser)
              $connInfo = $connInfo.$rbisUser->Entity->getFirstname()." ".$rbisUser->Entity->getLastname()." (".$rbisUser->getEmailaddress().")"."###";

      echo $connInfo;
      return sfView::NONE;
    }

    public function executeAddCollaborativeUser(sfWebRequest $request)
    {
        // If true then it returns collaborators' list in LIST VIEW (ref: PublicationView screen)
        $formatByList = $request->getParameter('formatByList');

        $researchId = $request->getParameter('rid');
        $collaborativeUserInfo = $request->getParameter('uDetail');

        $collaborativeUserEmail = substr($collaborativeUserInfo, strrpos($collaborativeUserInfo, '(') + 1, -1);
        $collaborativeUser = Entity::GetEntityByEmail( $collaborativeUserEmail );

        // If user already collaborating for this research then show error message
        if(Researchgroup::isUserCollaboratingForThisResearch($collaborativeUser->getId(), $researchId))
        {
            // Appeding 0 at the start so that in javascript we can easily track
            // that user already collaborating and can display warning message
            echo '0'.$this->getFormattedResearhGroupList($researchId, isset ($formatByList)? TRUE:FALSE);
        }
        else if(Researchgroup::isUserCollaboratingRequestPending ($collaborativeUser->getId(), $researchId))
        {
            // Appeding 1 at the start so that in javascript we can easily track
            // that user collaboration request is pedning can display warning message
            echo '1'.$this->getFormattedResearhGroupList($researchId, isset ($formatByList)? TRUE:FALSE);
        }
        else
        {
            $newCollaboratorUser = Researchgroup::addNewCollaborativeUser($researchId, $collaborativeUser->getId(), $this->getUser()->getAttribute("currentuser")->getId());

            // If collaborative user added successfully
            if(isset ($newCollaboratorUser))
            {
                $collaboratorUserKey = Configurationtoken::generateToken( $newCollaboratorUser->getId(), Types::$EMAIL_FORMAT['USER COLLABORATION ALERT']);
                $approveCollaborationUrl = 'http://'.$request->getHost().'/publication/approveCollaborationRequest?toc='. $collaboratorUserKey;
                $cancelCollaborationUrl = 'http://'.$request->getHost().'/publication/cancelCollaborationRequest?toc='.  $collaboratorUserKey;

                // If collaborating user added successfully, then send an alert email to user
                RBISUtility::sendEmail($collaborativeUserEmail, 'RBIS ALERT', sprintf( Emailformat::getEmailFormat(Types::$EMAIL_FORMAT['USER COLLABORATION ALERT']),$collaborativeUser->getFullname(), $this->getUser()->getAttribute("currentuser")->getFullname(), Research::getResearch($researchId)->getTitle(), $approveCollaborationUrl, $cancelCollaborationUrl), $this->getUser()->getAttribute("currentuser")->getId());
                echo $this->getFormattedResearhGroupList($researchId, isset ($formatByList)? TRUE:FALSE);
            }
        }

        return sfView::NONE;
    }

    public function executeApproveCollaborationRequest(sfWebRequest $request) {
        $tokenKey = $request->getParameter('toc');
        $token = Configurationtoken::getToken($tokenKey, Types::$EMAIL_FORMAT['USER COLLABORATION ALERT']);
        
        // Redirect to error if no user in session
        $this->forward404Unless($token, sprintf('Invalid Request (%s).', ''));

        Researchgroup::updateCollaborationInvitationStatus($token->getTokenvalue(), Types::$COLLABORATION_REQUEST_STATUS[Types::$COLLABORATION_REQUEST_STATUS_APPROVED]);

        // Forward to HOME PAGE
        $this->redirect('home/index');

        return sfView::NONE;
    }

    public function executeCancelCollaborationRequest(sfWebRequest $request) {
        $tokenKey = $request->getParameter('toc');
        $token = Configurationtoken::getToken($tokenKey, Types::$EMAIL_FORMAT['USER COLLABORATION ALERT']);

        // Redirect to error if no user in session
        $this->forward404Unless($token, sprintf('Invalid Request (%s).', ''));

        Researchgroup::updateCollaborationInvitationStatus($token->getTokenvalue(), Types::$COLLABORATION_REQUEST_STATUS[Types::$COLLABORATION_REQUEST_STATUS_REJECTED]);

        // Forward to HOME PAGE
        $this->redirect('home/index');

        return sfView::NONE;
    }

    private function getFormattedResearhGroupList($reseachId, $formatByListView)
    {
        $research = Research::getResearch($reseachId);
        $researchGroupList = $research->getCollaboratorList(array( Types::$COLLABORATION_REQUEST_STATUS[Types::$COLLABORATION_REQUEST_STATUS_REJECTED] ), TRUE);
        $formmatedRGoup = '';

        // If no user is collaborating then return empty space to remove
        // AJAX loading image from screen
        if($researchGroupList->count() == 0)
        {
            $formmatedRGoup .= '&nbsp;';
        }
        else
        {
            $totalCollaborators = $researchGroupList->count();
            $tempIndex = 0;

            if(!$formatByListView)
            {
                $formmatedRGoup .= '<label>Collaborator(s):</label>';
                foreach($researchGroupList as $researchGroup)
                {
                    $tempIndex++;
                    $formmatedRGoup .= '<span>';
                    $formmatedRGoup .= ('<a href="'. $this->getController()->genUrl('home/userProfile?id='.RBISUtility::encryptURLParamValue($researchGroup->getCollaborativeentityid())) . '">');
                    $formmatedRGoup .= Entity::GetEntity( $researchGroup->getCollaborativeentityid())->getFullname();
                    $formmatedRGoup .= '</a>';

                    if($researchGroup->getCollaborationrequesttyperefid() == Types::$COLLABORATION_REQUEST_STATUS[Types::$COLLABORATION_REQUEST_STATUS_APPROVED])
                            $formmatedRGoup .= '<a class="clickable" onclick="return removeCollaborativeUser('.$researchGroup->getCollaborativeentityid().','.$research->getId().');">(Remove)</a>';
                    elseif($researchGroup->getCollaborationrequesttyperefid() == Types::$COLLABORATION_REQUEST_STATUS[Types::$COLLABORATION_REQUEST_STATUS_PENDING])
                            $formmatedRGoup .= '(Pending/<a class="clickable" onclick="return removeCollaborativeUser('.$researchGroup->getCollaborativeentityid().','.$research->getId().');">Remove</a>)';

                    // Removing the last comma from collaborator list
                    if($tempIndex < $totalCollaborators)
                        $formmatedRGoup .= '<label>, </label>';
                    $formmatedRGoup .= '</span>';
                }

                // Destroying variables
                unset ($totalCollaborators);
                unset ($tempIndex);

            }
            else
            {
                $formmatedRGoup .= '<span class="abstractHeading">Collaborator(s)</span>';
                $formmatedRGoup .= '<ul>';
                foreach($researchGroupList as $researchGroup)
                {
                    $formmatedRGoup .= '<li>';
                    $formmatedRGoup .= ('<a href="'. $this->getController()->genUrl('home/userProfile?id='.RBISUtility::encryptURLParamValue($researchGroup->getCollaborativeentityid())) . '">');

                    $formmatedRGoup .= Entity::GetEntity($researchGroup->getCollaborativeentityid())->getFullname();

                    if($researchGroup->getCollaborationrequesttyperefid() == Types::$COLLABORATION_REQUEST_STATUS[Types::$COLLABORATION_REQUEST_STATUS_APPROVED])
                            $formmatedRGoup .= '<a class="clickable" onclick="return removeCollaborativeUser('.$researchGroup->getCollaborativeentityid().','.$research->getId().');">(Remove)</a>';
                    elseif($researchGroup->getCollaborationrequesttyperefid() == Types::$COLLABORATION_REQUEST_STATUS[Types::$COLLABORATION_REQUEST_STATUS_PENDING])
                            $formmatedRGoup .= '(Pending/<a class="clickable" onclick="return removeCollaborativeUser('.$researchGroup->getCollaborativeentityid().','.$research->getId().');">Remove</a>)';

                    $formmatedRGoup .= '</a>';
                    $formmatedRGoup .= '</li>';

                }
                $formmatedRGoup .= '</ul>';
            }
            
        }

        // Destroying objects
        unset ($research);
        unset ($researchGroupList);
        
        return $formmatedRGoup;
    }

    public function executeRemoveCollaborativeUser(sfWebRequest $request){

        $researchId = $request->getParameter('rid');
        $collaborativeUserId = $request->getParameter('cuid');

        if(isset ($researchId) && isset ($collaborativeUserId))
        {
            // Removes the selected collaborative user from said research
            $isUserDeleted = Researchgroup::removeCollaborativeUser($collaborativeUserId, $researchId);

            if($isUserDeleted)
                echo $this->getFormattedResearhGroupList($researchId);
        }
        return sfView::NONE;
    }

    public function executeViewPublication(sfWebRequest $request) {
        $researchId = $request->getParameter('id');

        if(isset ($researchId))
        {
            $research = Research::getResearch($researchId);

            // Redirect to error page if no research found
            $this->forward404Unless($research, sprintf('Research does not exist (%s).', ''));

            $this->research = $research;
        }
        return sfView::SUCCESS;
    }

    /*
     * Sets the publication status Approved/Rejected
     * Used by Professor group only
     */
    public function executeSetPublicationApprovalStatus(sfWebRequest $request) {
        
        $researchId = $request->getParameter('rid');
        
        $approvalStatus = $request->getParameter('status');
        
        $selectTabValue = $request->getParameter('tid');
        
        $researchSearchtext = $request->getParameter('rSearchtext');
        
        $pgNumber = $request->getParameter('pg');
        
        $entityId = $request->getParameter('id');

        $research = Research::getResearch($researchId);

        if(isset ($research))
        {
            $research->updateApproval($approvalStatus, array('profid' => $this->getUser()->getAttribute('currentuser')->getId()));
            //$research->setApprovalStatus($approvalStatus, $this->getUser()->getAttribute('currentuser')->getId());

            //$this->forward('publication', 'refreshRBISResearchList?tid='.$selectTabValue.'&pg='.$pgNumber.'&id='.$entityId.'&rSearchtext='.$researchSearchtext);
            //$this->forward('publication','refreshRBISResearchList?tid='.$selectTabValue.'&pg='.$pgNumber.'&id='.$entityId.'&rSearchtext='.$researchSearchtext);

            $this->getRequest()->setParameter('tid', $selectTabValue);
            //$this->getRequest()->setParameter('pg', $pgNumber);
            $this->getRequest()->setParameter('uid', $entityId);
            $this->getRequest()->setParameter('st', TRUE);
            //$this->getRequest()->setParameter('rSearchtext', $researchSearchtext);
            $this->forward('publication', 'loadpublications');
        }
        return sfView::NONE;
    }
}
